﻿using System;
using Present.Commands.Rx;

namespace Present.Commands.Async.Actions.Decorators
{
    public interface IObservableCommandAction : IAsyncAction, IObservable<object>
    {

    }

    /// <summary>
    /// Wraps a Target with Observable Semantics for use with RX
    /// </summary>
    public class ObservableAsyncActionDecorator<TParameter, TResult> : AsyncActionDecorator<TParameter, TResult>, IObservableCommandAction
    {
        private readonly ObservableSubscription<object> observable;

        public ObservableAsyncActionDecorator(IAsyncAction<TParameter, TResult> target) : base(target)
        {
            observable = new ObservableSubscription<object>();
        }

        public override void HandleSuccess(TResult result)
        {
           base.HandleSuccess(result);
            observable.Next(result);
            observable.Complete();
        }


        public override void HandleError(Exception error)
        {
           observable.Error(error);
           base.HandleError(error);
        }

        
        

        public IDisposable Subscribe(IObserver<object> observer)
        {
            return observable.Subscribe(observer);
        }
    }
}